//-----调试的话，主线程+join;
#include <thread>
#include <functional>
#include <iostream>
//thread 线程创建，注意调试的时候，main 函数要携程join；
using namespace std;
//多线程循环打印数字；

class Solution{
public:
    Solution(){
        produce_thread=std::thread([this](){
            produce();
        });
        consume_thread=std::thread([this](){
            consume();
        });
        auto func=std::bind(&Solution::consume,this);
        t3=std::thread(func);
    }
    void produce(){
        std::cout << "hello world" << std::endl;
    }
    void consume(){
        std::this_thread::sleep_for(std::chrono::seconds(5));
        std::cout << "world end" << std::endl;
    }
    void join(){
        produce_thread.join();
        consume_thread.join();
        t3.join();
    }
    ~Solution(){
    }
private:
    std::thread produce_thread;
    std::thread consume_thread;
    std::thread t3;
};
//函数传参
void process_data(std::vector<int>&& data) {
    for (int value : data) {
        std::cout << "Value: " << value << std::endl;
    }
}

int main() {
    std::vector<int> data = {1, 2, 3, 4, 5};

    // 创建线程并传递右值引用参数
    std::thread t(process_data, std::move(data));


    // 使用std::thread启动线程
    std::thread t( [](){
       std::cout << "Hello from thread!" << std::endl;
    });

    // 等待线程完成
    t.join();

    return 0;
}

#include <iostream>
#include <thread>
#include <functional>

class MyClass {
public:
    void my_member_function(int value) {
        std::cout << "Member function called with value: " << value << std::endl;
    }
};

int main() {
    MyClass obj;
    int value_to_pass = 42;

    // 使用 std::bind 创建一个绑定对象，该对象包含成员函数和其所需的参数
    auto bound_member_function = std::bind(&MyClass::my_member_function, &obj, value_to_pass);

    // 将绑定对象传递给 std::thread 构造函数
    std::thread t(bound_member_function);

    // 等待线程完成
    t.join();

    return 0;
}



#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
int counter = 1;

void printNumber(int id, int max) {
    while (true) {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [id, max] { return counter % max == id; });
        std::cout << "Thread " << id << ": " << counter << std::endl;
        ++counter;
        lock.unlock();
        cv.notify_all();
    }
}

int main() {
    const int numThreads = 3;
    std::thread threads[numThreads];

    for (int i = 0; i < numThreads; ++i) {
        threads[i] = std::thread(printNumber, i, numThreads);
    }

    for (int i = 0; i < numThreads; ++i) {
        threads[i].join();
    }

    return 0;
}
